package com.wxit.algorithm.tree;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 前序遍历
 */
public class LeetCode144 {

    public List<Integer> preorderTraversal(TreeNode root) {
        LinkedList<TreeNode> stack = new LinkedList<>();
        List<Integer> result = new ArrayList<>();
        TreeNode curr = root; //代表当前节点
        TreeNode pop = null; //最近一次弹栈的元素
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                //处理左子树
                result.add(curr.val);
                curr = curr.left;

            } else {
                TreeNode peek = stack.peek();
                //没有右子树
                if (peek.right == null) {
                    pop = stack.pop();
                }
                //已经处理过右子树
                else if (peek.right == pop) {
                    pop = stack.pop();
                }
                //待处理右子树
                else {
                    curr = peek.right;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode( new TreeNode(new TreeNode(4), 2, null),
                1,
                new TreeNode(new TreeNode(5), 3, new TreeNode(6))
        );

        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode curr = root; //代表当前节点
        TreeNode pop = null; //最近一次弹栈的元素
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.push(curr);
                //处理左子树
                colorPrintln("前:" + curr.val, 31);
                curr = curr.left;

            } else {
                TreeNode peek = stack.peek();
                //没有右子树
                if (peek.right == null) {
                    colorPrintln("中:" + peek.val, 36);
                    pop = stack.pop();
                    colorPrintln("后:" + pop.val, 34);
                }
                //已经处理过右子树
                else if (peek.right == pop) {
                    pop = stack.pop();
                    colorPrintln("后:" + pop.val, 34);
                }
                //待处理右子树
                else {
                    colorPrintln("中:" + peek.val, 36);
                    curr = peek.right;
                }
            }
        }
    }

    private static void colorPrintln(String origin, int color) {
        System.out.printf("\033[%dm%s\033[0m%n", color, origin);
    }
}
